import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Card, Row, Col, Input, Select, Button,
} from 'antd';

import { DetailInfoItem } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
interface CooperationSaveProps extends FormComponentProps {
    dispatch: Dispatch;
    dataInfo: DetailInfoItem;
    loading: boolean;
    INITINFO: any;
    location: { query: any };
}

interface CooperationSaveState {
    companyID: number;
    type: number;
    logisType: number;
    perLogisType: number | string;
    formValus: any;
}

@connect(({
    cooperationCompanyAdd: { dataInfo },
    common: { INITINFO },
}: any) => ({
    dataInfo,
    INITINFO,
}))
class CooperationSaveInfoElem extends Component<CooperationSaveProps, CooperationSaveState> {
    state: CooperationSaveState = {
        companyID: 1,
        type: 1,
        logisType: 1,
        perLogisType: '',
        formValus: {},
    };

    static getDerivedStateFromProps(nextProps: CooperationSaveProps, preState: CooperationSaveState) {
        const { companyID } = preState;
        const { dataInfo } = nextProps;
        const { perLogisType } = preState;
        if ((dataInfo.pcId && perLogisType !== dataInfo.type)
            || (dataInfo.pcId && companyID !== dataInfo.pcId)
        ) {
            return {
                companyID: dataInfo.pcId,
                type: dataInfo.type,
                logisType: dataInfo.type,
                perLogisType: dataInfo.type,
            };
        }
        return null;
    }

    componentDidMount() {
        const {
            location: { query: { id } },
        } = this.props;
        if (id) this.fetchDetailInfo(id);

        this.fetchAction('common/fetchPartner');
        this.fetchAction('common/fetchGardenList');
        this.fetchAction('common/fetchLogisList');
    }

    componentDidUpdate(prevProps: any) {
        const {
            location: { query: { id } },
        } = this.props;
        if (id && id !== prevProps.location.query.id) {
            this.fetchDetailInfo(id);
        }
    }

    componentWillUnmount() {
        this.fetchAction('clear');
    }

    fetchDetailInfo = (id: number) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'cooperationCompanyAdd/fetch',
            payload: { id },
        });
    };

    handleChangePC = (companyID: number) => {
        this.setState({ companyID });

        if (companyID === 6) {
            const { form: { resetFields } } = this.props;
            resetFields(['type']);
        }
    };

    handleChangeType = (logisType: number) => this.setState({ logisType });

    handleSelectLog = (id: number, e: any) => {
        const { formValus } = this.state;
        const params = {
            logisId: id,
            logisCode: e.key,
            logisName: e.props.children,
        };
        this.setState({ formValus: { ...formValus, ...params } });
    };

    handleSubmit = () => {
        const { formValus } = this.state;
        const { form: { validateFieldsAndScroll } } = this.props;
        validateFieldsAndScroll((errors, values) => {
            if (errors) return;

            const { garden, logis } = values;
            const params = {
                ...values,
                ...formValus,
                gardenId: garden ? garden.key : '',
                gardenName: garden ? garden.label : '',
                logisId: logis ? logis.key : '',
                logisName: logis ? logis.label : '',
                serviceTime: '00:00-23:59',
            };

            delete params.logis;
            delete params.garden;
            delete params.serviceStartTime;
            delete params.serviceEndTime;

            const { location: { query } } = this.props;
            if (query) params.id = query.id;
            this.fetchAction('saveOrUpdatePartner', params);
        });
    };

    fetchAction = (typeName: string, payload: any = {}) => {
        const { dispatch } = this.props;
        const type = typeName.indexOf('common') >= 0
            ? typeName : `cooperationCompanyAdd/${typeName}`;
        dispatch({ type, payload });
    };

    render() {
        const { companyID, type, logisType } = this.state;
        const {
            form: { getFieldDecorator },
            dataInfo,
            INITINFO: { gardenList, logisList, partnerList },
            location: { query },
        }: any = this.props;

        const disabled = Boolean(dataInfo.code);

        return (
            <Fragment>
                <PageHeader />

                <Card bordered={false}>
                    <Form hideRequiredMark className="tableListForm">
                        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                            <Col md={8} sm={24}>
                                <Item label="快递公司" colon={false}>
                                    {getFieldDecorator('pcId', {
                                        initialValue: companyID,
                                        rules: [{ required: true, message: '请选择快递公司' }],
                                    })(
                                        <Select
                                            allowClear
                                            placeholder="请选择"
                                            disabled={Boolean(query.id)}
                                            onChange={this.handleChangePC}
                                        >
                                            {partnerList.map((item: any) => {
                                                if (item.id !== 3) {
                                                    return (
                                                        <Option value={item.id} key={item.id}>
                                                            {item.name}
                                                        </Option>
                                                    );
                                                }
                                                return false;
                                            })}
                                        </Select>,
                                    )}
                                </Item>
                            </Col>
                        </Row>
                        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                            <Col md={8} sm={24}>
                                <Item label="　　类型" colon={false}>
                                    {getFieldDecorator('type', {
                                        initialValue: type,
                                        rules: [{ required: true, message: '请选择类型' }],
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            disabled={Boolean(query.id)}
                                            onChange={this.handleChangeType}
                                        >
                                            <Option value={1}>物流中心</Option>
                                            <Option disabled={[1, 6].includes(companyID)} value={3}>
                                                小区
                                            </Option>
                                        </Select>,
                                    )}
                                </Item>
                            </Col>
                        </Row>
                        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                            <Col md={8} sm={24}>
                                {logisType === 1 && (
                                    <Item label="物流中心" colon={false}>
                                        {getFieldDecorator('logis', {
                                            initialValue: dataInfo.logisId && {
                                                key: dataInfo.logisId,
                                                label: dataInfo.logisName,
                                            },
                                            rules: [{ required: true, message: '请选择物流中心' }],
                                        })(
                                            <Select
                                                showSearch
                                                placeholder="请选择"
                                                labelInValue
                                                disabled={Boolean(query.id)}
                                                onChange={this.handleSelectLog}
                                                filterOption={(input: any, option: any) => option.props.children
                                                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            >
                                                {logisList.map((item: any) => (
                                                    <Option value={item.id} key={item.id}>
                                                        {item.name}
                                                    </Option>
                                                ))}
                                            </Select>,
                                        )}
                                    </Item>
                                )}
                                {logisType !== 1 && (
                                    <Item label="校园小区" colon={false}>
                                        {getFieldDecorator('garden', {
                                            initialValue: dataInfo.gardenId && {
                                                key: dataInfo.gardenId,
                                                label: dataInfo.gardenName,
                                            },
                                            rules: [{ required: true, message: '请选择校园小区' }],
                                        })(
                                            <Select
                                                showSearch
                                                placeholder="请选择"
                                                labelInValue
                                                disabled={Boolean(query.id)}
                                                filterOption={(input: any, option: any) => option.props.children
                                                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            >
                                                {gardenList.map((item: any) => (
                                                    <Option value={item.id} key={item.id}>
                                                        {item.name}
                                                    </Option>
                                                ))}
                                            </Select>,
                                        )}
                                    </Item>
                                )}
                            </Col>
                        </Row>
                        {[1].includes(companyID) && (
                            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                                <Col md={8} sm={24}>
                                    <Item label="网点编码" colon={false}>
                                        {getFieldDecorator('code', {
                                            initialValue: dataInfo.code,
                                            rules: [{ required: true, message: '请输入网点编码' }],
                                        })(<Input allowClear placeholder="请输入" disabled={disabled} />)}
                                    </Item>
                                </Col>
                            </Row>
                        )}
                        {![6, 7, 78, 79].includes(companyID) && (
                            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                                <Col md={8} sm={24}>
                                    <Item label="　联系人" colon={false}>
                                        {getFieldDecorator('contact', {
                                            initialValue: dataInfo.contact,
                                            rules: [{ required: true, message: '请输入联系人' }],
                                        })(<Input allowClear placeholder="请输入" />)}
                                    </Item>
                                </Col>
                            </Row>
                        )}
                        {!([6, 79].includes(companyID) || (companyID === 78 && logisType !== 1)) && (
                            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                                <Col md={8} sm={24}>
                                    <Item label="联系电话" colon={false}>
                                        {getFieldDecorator('phone', {
                                            initialValue: dataInfo.phone,
                                            rules: [{ required: true, message: '请输入联系电话' }],
                                        })(<Input allowClear placeholder="请输入" />)}
                                    </Item>
                                </Col>

                            </Row>
                        )}
                        {!disabled && (
                            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                                <Col md={8} sm={24}>
                                    <Item label="　　状态" colon={false}>
                                        {getFieldDecorator('status', {
                                            initialValue: dataInfo.status || 1,
                                            rules: [{ required: true, message: '请选择状态' }],
                                        })(
                                            <Select placeholder="请输入">
                                                <Option value={1}>有效</Option>
                                                <Option value={0}>无效</Option>
                                            </Select>,
                                        )}
                                    </Item>
                                </Col>
                            </Row>
                        )}
                        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                            <Col md={12} sm={24}>
                                <Button
                                    type="primary"
                                    onClick={this.handleSubmit}
                                >
                                    保存
                                </Button>
                                <Button
                                    ghost
                                    type="primary"
                                    className="marginL16"
                                    onClick={() => router.goBack()}
                                >
                                    取消
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                </Card>
            </Fragment>
        );
    }
}

export default Form.create<CooperationSaveProps>()(CooperationSaveInfoElem);
